package star.oath.project;

import java.util.*;

public class WeightedRandomPicker {

    /**
     * 随机选择一个元素，权重为 weights 中的元素
     * @param list 待选择的元素列表
     * @param weights 每个元素对应的权重
     * @return 随机选择的元素
     */
    public static <T> T pickOne(List<T> list, List<Integer> weights) {
        if (list.size() != weights.size() || list.size() == 0) {
            return null;
        }
        // 计算总权重
        int totalWeight = 0;
        for (int w : weights) {
            totalWeight += w;
        }
        // 生成 [1, totalWeight] 范围内的随机数（闭区间）
        Random rand = new Random();
        int randomNumber = rand.nextInt(totalWeight) + 1; // 注意：+1 是为了从1开始
        // 累加权重，找到对应区间
        int cumulativeWeight = 0;
        for (int i = 0; i < weights.size(); i++) {
            cumulativeWeight += weights.get(i);
            if (randomNumber <= cumulativeWeight) {
                return list.get(i);
            }
        }
        // 理论上不会到这里
        return null;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        List<Integer> weights = new ArrayList<>();
        weights.add(1);
        weights.add(2);
        weights.add(3);
        weights.add(4);

        Map<String, Integer> map = new HashMap<>();
        for (int i = 1; i <= 100; i++) {
            String key = pickOne(list, weights);
            map.put(key, map.getOrDefault(key, 0) + 1);
            System.out.println(i+":"+key);
        }
        System.out.println(map);
    }

}